﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Web_froms
{
    public partial class _Default : Page
    {
        public static DataTable dt = new DataTable();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Filldata();
            }
        }

        private void Filldata()
        {
            var sql = "select Id,Title,Content,Author,Remarks from Articles";
            var dt = DbHelper.GetDatatable(sql);

            gv1.DataSource = dt;
            gv1.DataBind();
        }


        //编辑
        protected void gv1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gv1.EditIndex = e.NewEditIndex;
            Filldata();
        }

        //取消
        protected void gv1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gv1.EditIndex = -1;
            Filldata();
        }

        //更新
        protected void gv1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var idstr = GetCellValue(e.RowIndex, 0);
            var isok = int.TryParse(idstr, out int id);
            var title = GetCellValue(e.RowIndex, 1);
            var content = GetCellValue(e.RowIndex, 2);
            var author = GetCellValue(e.RowIndex, 3);
            var remarks = GetCellValue(e.RowIndex, 4);
            if (isok)
            {
            var sql = string.Format("update Articles set Title='{0}',Content='{1}',Author='{2}',Remarks='{3}'where Id={4}", title, content, author, remarks, id);
            DbHelper.ADU(sql);
            }
            else
            {
                var sql = string.Format("insert into Articles (Title,Content,Author,Remarks) values ('{0}','{1}','{2}',{3})", title, content, author, remarks);
                DbHelper.ADU(sql);
            }

            gv1.EditIndex = -1;
            Filldata();
        }

        public string GetCellValue(int rowIndex,int colIndex)
        {
            var cell = gv1.Rows[rowIndex].Cells[colIndex];
            var str = cell.Controls.Count > 0 ? ((TextBox)cell.Controls[0]).Text : cell.Text;
            return str;
        }

        //删除
        protected void gv1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var id = GetCellValue(e.RowIndex, 0);
            var sql = string.Format("delete Articles where Id={0}", id);
            DbHelper.ADU(sql);
            Filldata();
        }

        //新增
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            var newdt = dt.Copy();
            newdt.Rows.Add(newdt.NewRow());
            dt = newdt;
            gv1.DataSource = newdt;
            gv1.DataBind();
            gv1.EditIndex = newdt.Rows.Count - 1;
            gv1.DataSource = newdt;
            gv1.DataBind();
        }
    }
}